package com.ruoyi.project.digital.service.impl;

import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.EnvUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.domain.Result;
import com.ruoyi.project.common.component.AliOssProperties;
import com.ruoyi.project.digital.domain.*;
import com.ruoyi.project.digital.domain.dto.CommityDto;
import com.ruoyi.project.digital.domain.dto.RegisterDto;
import com.ruoyi.project.digital.domain.enums.*;
import com.ruoyi.project.digital.service.*;
import com.ruoyi.project.system.service.ISysConfigService;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.digital.mapper.TUserMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-28
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService
{
    @Autowired
    private IMoodPetService moodPetService;
    @Autowired
    private IUserPetService userPetService;
    @Autowired
    private IUserBackService userBackService;
    @Autowired
    private ITBackService backService;
    @Autowired
    private AliOssProperties ossProperties;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IPetService petService;
    @Autowired
    private IUserTaskService userTaskService;
    @Autowired
    private ITUserService userService;
    @Autowired
    private INoticeService noticeService;

    /**
     * 查询用户
     *
     * @param id 用户ID
     * @return 用户
     */
    @Override
    public TUser selectTUserById(Long id)
    {
        return baseMapper.selectTUserById(id);
    }

    /**
     * 查询用户列表
     *
     * @param tUser 用户
     * @return 用户
     */
    @Override
    public List<TUser> selectTUserList(TUser tUser)
    {
        return baseMapper.selectTUserList(tUser);
    }

    /**
     * 新增用户
     *
     * @param tUser 用户
     * @return 结果
     */
    @Override
    public int insertTUser(TUser tUser)
    {
        return baseMapper.insertTUser(tUser);
    }

    /**
     * 修改用户
     *
     * @param tUser 用户
     * @return 结果
     */
    @Override
    public int updateTUser(TUser tUser)
    {
        return baseMapper.updateTUser(tUser);
    }

    /**
     * 批量删除用户
     *
     * @param ids 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteTUserByIds(Long[] ids)
    {
        return baseMapper.deleteTUserByIds(ids);
    }

    /**
     * 删除用户信息
     *
     * @param id 用户ID
     * @return 结果
     */
    @Override
    public int deleteTUserById(Long id)
    {
        return baseMapper.deleteTUserById(id);
    }

    @Override
    public TUser selectByOpenId(String openid) {
        QueryWrapper<TUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name",openid);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setMood(Long id,Long moodId) {
        //更新用户当前心情
        TUser user = new TUser();
        user.setId(id);
        user.setMoodId(moodId);
        updateById(user);
        //根据心情查询当前的宠物
        QueryWrapper<MoodPet> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("mood_id",moodId);
        MoodPet moodPet=  moodPetService.getOne(queryWrapper);
        //插入一条用户的宠物信息
        QueryWrapper<UserPet> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("pet_id", moodPet.getPetId());
        queryWrapper1.eq("user_id", id);
        UserPet check = userPetService.getOne(queryWrapper1);
        if(ObjectUtil.isNull(check)){
            UserPet userPet=new UserPet();
            userPet.setPetId(moodPet.getPetId());
            userPet.setUserId(id);
            userPetService.save(userPet);
        }

    }

    /**
     * 处理第三方接口
     * @param commityDto
     */
    @Override
    public void handerThridCommity(CommityDto commityDto) {
//        TUser user=   selectByOpenId(commityDto.getMobile());
        switch (commityDto.getType()){
            case "背景":
                handerBjOrZs(commityDto);
            case "装饰":
                handerBjOrZs(commityDto);
            case "宠物":
                handerCw(commityDto);
            case "体力":
                handerTl(commityDto);

        }
    }

    @Override
    public TUser getByPhone(String phone) {
        return null;
    }

    @Override
    public TUser getEmail(String phone) {
        return null;
    }

    @Override
    public TUser getUserName(String phone) {
        QueryWrapper<TUser> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("user_name",phone);
        TUser user=getOne(userQueryWrapper);
        return user;
    }

    @Override
    public Result register(RegisterDto registerDto) {
        // 判断手机号是否注册过了
        TUser one = getUserName(registerDto.getPhone());
        if (one != null) {
            return Result.error("该账号已经注册");
        }
      // 校验验证码  TODO 后期更改为真实数据

        String key = Constants.REDIS_PRE_SMS + registerDto.getPhone();
        String verifyCode=null;
        //String key = "1234";
        if(EnvUtil.isDev()){
             verifyCode ="123456";
        }else{
            verifyCode  =registerDto.getSmsCode();
        }
        if (StringUtil.isBlank(verifyCode)) {
            // 短信验证码已过期
            return Result.error("验证码错误");
        } else if (!registerDto.getSmsCode().equals(verifyCode)) {
            // 短信验证码验证失败
            return Result.error("验证码错误");
        }

        TUser wechatUser = new TUser();
        wechatUser.setUserName(registerDto.getPhone());
        wechatUser.setPassword(SecurityUtils.encryptPassword(registerDto.getPassword()));
        wechatUser.setBackGroup(ossProperties.getPreview()+Constants.DEAFULT_BACK_IMG);
        wechatUser.setIsInit(IsInitEmum.NO.getValue());
        wechatUser.setIsLine(IsLineEmum.YES.getValue());
        if (null != registerDto.getWeixinId()){
            wechatUser.setWeixinId(registerDto.getWeixinId());
        }
        if (null != registerDto.getQqId()){
            wechatUser.setQqId(registerDto.getQqId());
        }
        insertTUser(wechatUser);
        String syskey=   configService.selectConfigByKey(com.ruoyi.project.digital.domain.Constants.BACK_URL);
        UserBack userBack=new UserBack();
        TBack back=backService.getById(syskey);
        userBack.setBackUrl(back.getUrl());
        userBack.setBackId(back.getId());
        userBack.setIsDeafult(YesOrNoStatus.YES.getValue().toString());
        userBack.setUserId(wechatUser.getId());
        userBackService.save(userBack);
        return Result.success();
    }

    /**
     * 更新体力
     * @param commityDto
     */
    private void handerTl(CommityDto commityDto) {
        TUser tUser = perform(commityDto);
        tUser.setResStamina(Long.valueOf(tUser.getResStamina()+commityDto.getMerit()));
        updateById(tUser);
        createNotice(commityDto);
    }

    /**
     * 更新背景和装饰
     * @param commityDto
     */
    private void handerBjOrZs(CommityDto commityDto) {
        String type = "背景".equals(commityDto.getType()) ? "1":"2";
        TUser tUser = perform(commityDto);
        QueryWrapper<TBack> backQueryWrapper = new QueryWrapper<>();
        backQueryWrapper.eq("code",commityDto.getKeyword());
        // 向背景表插入商品数据
        if (null == backService.getOne(backQueryWrapper)){
            TBack back=new TBack();
            back.setIsEnable(YesOrNoStatus.YES.getValue().toString());
            back.setUrl(commityDto.getImageUrl());
            back.setCode(commityDto.getKeyword());
            back.setType(type);
            back.setCreateTime(new Date());
            backService.save(back);
        }
        QueryWrapper<UserBack> userBackQueryWrapper = new QueryWrapper<>();
        userBackQueryWrapper.eq("code",commityDto.getKeyword()).eq("user_id",tUser.getId());
        // 向用户背景表插入商品数据
        if (null == userBackService.getOne(userBackQueryWrapper)){
            UserBack userBack=new UserBack();
            userBack.setUserId(tUser.getId());
            userBack.setCode(commityDto.getKeyword());
            userBack.setIsDeafult("1");
            userBack.setType(type);
            userBackService.save(userBack);
        }
        createNotice(commityDto);
    }

    /**
     * 更新宠物
     * @param commityDto
     */
    private void handerCw(CommityDto commityDto){
        QueryWrapper<Pet> petQueryWrapper = new QueryWrapper<>();
        petQueryWrapper.eq("code",commityDto.getKeyword());
        // 向宠物表中插入商品数据
        if (null == petService.getOne(petQueryWrapper)){
            Pet pet = new Pet();
            pet.setPetName(commityDto.getStoreName());
            pet.setIsEnable("0");
            pet.setPetUrl(commityDto.getImageUrl());
            petService.insertPet(pet);
        }
        createNotice(commityDto);
    }

    // 完成购买任务
    private TUser perform(CommityDto commityDto){
        QueryWrapper<TUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name",commityDto.getMobile());
        TUser tUser = userService.getOne(userQueryWrapper);
        UpdateWrapper<UserTask> wrapper = new UpdateWrapper<>();
        wrapper.eq("title","购买商品").eq("user_id",tUser.getId());
        wrapper.set("status", UserTaskStatusEnum.FINISH.getValue());
        userTaskService.update(wrapper);
        return tUser;
    }

    // 插入一条消息通知
    private void createNotice(CommityDto commityDto){
        QueryWrapper<TUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name",commityDto.getMobile());
        TUser tUser = userService.getOne(userQueryWrapper);
        Notice notice = new Notice();
        notice.setNoticeTitle("商品购买成功");
        notice.setCreateTime(new Date());
        notice.setShowType("0");
        notice.setAvterImage(commityDto.getImageUrl());
        notice.setChanel("0");
        notice.setContent(commityDto.getType()+commityDto.getStoreName()+"购买成功");
        notice.setCreateTime(new Date());
        notice.setIsRead("1");
        notice.setUserId(tUser.getId());
        noticeService.insertNotice(notice);
    }


    public static void main(String[] args) {
        System.out.println( SecurityUtils.encryptPassword("123456"));
    }
}
